from rest_framework.views import APIView
from rest_framework.response import Response
from user.models import User
from user.models import Token
import uuid


class Login(APIView):
    def post(self, request, *args, **kwargs):
        ret = {"code":4000}
        # try:
        username = request.data.get("username")
        password = request.data.get("password")

        # 加入密码校验功能
        user_obj = User.objects.filter(username=username,password=password).first()
        if user_obj:
            ret["code"] = 2000
            token = str(uuid.uuid4())
            Token.objects.update_or_create(user=user_obj, defaults={"token":token})
            ret["token"] = token
            ret["user_id"] = user_obj.id
        else:
            ret["code"] = 4004

            ret["error"] = "用户名密码错误"

        return Response(ret)
        # except:
        #     ret = {"state": 4000}
        #     ret["error"] = "系统错误！"
        #     return Response(ret)

